import { ref, reactive, computed, type FunctionalComponent as FC } from 'vue';
import Table from '@/components/table/index.vue';
import Dialog from '@/components/dialog/index.vue';
import SeriesTable from './seriesTable';
import SecondAlert from './secondAlert';
import type { SelectOptionData } from '@arco-design/web-vue';
import type {
  ProjectDetailStateForm,
  ViewBasicSetting,
  ViewAnnoSetting,
  ViewDataSetting,
  ViewAnnoUserSetting,
  SeriesDataItem,
  LesionDataList,
} from '@/store/modules/projectDetail/type';
import * as ApiTypes from '@/api/project/project.d';
import '../styles/stepForm.less';
import _ from 'lodash';

interface Prop {
  id: string;
  layout: string;
  status: string;
  type: 'create' | 'update';
  disabled: boolean;
  form: { basicSetting: ViewBasicSetting; annoSetting: ViewAnnoSetting };
  commonList: ApiTypes.CommonConfigResponse;
  compList: ApiTypes.CompConfigItem[];
  compTotal: number;
  toolList: ApiTypes.ToolConfigItem[];
  lesionList: ApiTypes.LesionConfigItem[];
  watchFormData: Function;
  getFormLeisonDataList: Function;
  clearLesionList: Function;
  getCompData: Function;
  getCompDialog: Function;
  sortAlertTableData: Function;
  clearAlertTableData: Function;
  setSelectCheckAll: Function;
  clearSelectCheckAll: Function;
  delCompAlertData: Function;
  delLesionData: Function;
  changeBizType: Function;
}

const visible = ref(false);
const functionExecuted = ref(false);
const current = ref(1);
const checkArr = ref({});
const secondVisible = ref(false);
const secondCurrentData = ref({} as SeriesDataItem);
const currentItem = ref({} as LesionDataList);
const currentItem_bak = ref({} as LesionDataList);

const AnnoTable: FC<Prop, any> = (props, ctx) => {
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      // width: 120,
      // fixed: 'left',
      slotName: 'index',
    },
    {
      title: '标注类型',
      dataIndex: 'name',
      // width: 240,
      // fixed: 'left',
      // ellipsis: true,
      // tooltip: true,
    },
    {
      title: '选择颜色',
      dataIndex: 'color',
      slotName: 'color',
    },
    {
      title: '标注工具',
      dataIndex: 'toolValueList',
      slotName: 'toolValueList',
      width: 290,
    },
    {
      title: '标注组件',
      dataIndex: 'imageFcList',
      slotName: 'imageFcList',
      width: 290,
    },
    {
      title: '病灶设置',
      dataIndex: 'bizType',
      slotName: 'bizType',
    },
    {
      title: '操作',
      dataIndex: 'action',
      slotName: 'action',
    },
  ];
  // 计算全选个数
  const getCheckAllList = () => {
    const checkAllNum = Math.ceil(props.compTotal / 10);
    for (let index = 1; index <= checkAllNum; index++) {
      checkArr.value[index] = {
        indeterminate: false,
        checked: false,
        page: index,
      };
    }
  };
  if (!functionExecuted.value) {
    getCheckAllList();
    functionExecuted.value = true;
  }
  // 已添加弹窗按钮点击
  const handleClick = (current: LesionDataList) => {
    currentItem.value = current;
    currentItem_bak.value = _.cloneDeep(current);
    visible.value = true;
  };
  // 已添加弹窗关闭
  const handleUpdateVisible = (callback) => {
    if(callback.status === 'save'){//确定
      //nothing to do
    }else if(callback.status === 'clear'){//取消
      // 改动不生效
      const index = props.form.annoSetting.lesionDataList.findIndex(it => it.lesionValue === currentItem.value.lesionValue)
      props.form.annoSetting.lesionDataList.splice(index, 1, currentItem_bak.value)
    }
    visible.value = false;
  };
  // 下拉分页操作
  const handlePageChange = (page: number) => {
    current.value = page;
    props.getCompData(page);
  };
  // 下拉全选操作
  const handleChange = (
    value: boolean,
    item: { indeterminate: boolean; checked: boolean; page: number },
    lesionValue: string
  ) => {
    item.indeterminate = false;
    item.checked = value;
    value && props.setSelectCheckAll(false, lesionValue);
    !value && props.clearSelectCheckAll(false, lesionValue);
  };
  // 下拉选项操作
  const handleSelectChange = async (
    values: number[],
    data: number[],
    value: string
  ) => {
    if (values.length !== 0) {
      props.getCompDialog(data, false, value);
    } else {
      props.clearAlertTableData(value);
    }
  };
  // 获取标签名称
  const getLabelData = (data: SelectOptionData, list: SeriesDataItem[]) => {
    const label = list.find((item) => item.id === data.value)?.name;
    return label;
  };
  // 查看标注字段弹窗点击
  const handleSecondClick = (data) => {
    secondCurrentData.value = data;
    secondVisible.value = true;
  };
  // 查看标注字段弹窗关闭
  const handleSecondUpdateVisible = () => {
    secondVisible.value = false;
  };
  return (
    <>
      <Table
        class="anno-table"
        columns={columns}
        bordered={true}
        pagination={false}
        showPagination={false}
        stickyHeader={true}
        data={props.form.annoSetting.lesionDataList}
        rowKey="lesionValue"
        v-slots={{
          index: ({ record, column, rowIndex }) => <div>{rowIndex + 1}</div>,
          color: ({ record, column, rowIndex }) => (
            <div>
              <el-color-picker
                v-model={record.color}
                disabled={props.disabled}
              />
            </div>
          ),
          toolValueList: ({ record, column, rowIndex }) => (
            <div>
              <a-select
                placeholder="请选择"
                multiple
                v-model={record.toolValueList}
                disabled={props.disabled}
              >
                {getOptions(
                  props.toolList,
                  rowIndex,
                  props.form.annoSetting.lesionDataList,
                  true
                )}
              </a-select>
            </div>
          ),
          imageFcList: ({ record, column, rowIndex }) => (
            <div>
              {/* onChange={handleChangeAll} */}
              <a-select
                placeholder="标注组件"
                v-model={record.imageList}
                multiple
                allow-clear
                max-tag-count={6}
                show-extra-options={false}
                disabled={props.disabled}
                onChange={(values) =>
                  handleSelectChange(
                    values,
                    record.imageList,
                    record.lesionValue
                  )
                }
                v-slots={{
                  // header: () => (
                  //   <div style="padding: 6px 12px;">
                  //     <a-checkbox
                  //       modelValue={checkArr.value[current.value].checked}
                  //       indeterminate={
                  //         checkArr.value[current.value].indeterminate
                  //       }
                  //       onChange={(value: boolean) =>
                  //         handleChange(
                  //           value,
                  //           checkArr.value[current.value],
                  //           record.lesionValue
                  //         )
                  //       }
                  //     >
                  //       全选{checkArr.value[current.value].page}
                  //     </a-checkbox>
                  //   </div>
                  // ),
                  footer: () => (
                    <div style="padding: 6px 12px;">
                      <a-pagination
                        v-model={current.value}
                        total={props.compTotal}
                        show-total
                        size="mini"
                        onChange={(current: number) =>
                          handlePageChange(current)
                        }
                      />
                    </div>
                  ),
                  label: ({ data }) => (
                    <div>{getLabelData(data, record.imageDataList)}</div>
                  ),
                }}
              >
                {getOptions(
                  changeData(props.compList),
                  rowIndex,
                  props.form.annoSetting.lesionDataList
                )}
              </a-select>
            </div>
          ),
          bizType: ({ record, column, rowIndex }) => (
            <div>
              <a-select
                placeholder="请选择"
                v-model={record.bizType}
                disabled={props.disabled}
                onChange={(value) =>
                  props.changeBizType(value, record.lesionValue)
                }
              >
                {getOpts(changeData(props.commonList.lesionBizTypes, true))}
              </a-select>
            </div>
          ),
          action: ({ record, column, rowIndex }) => (
            <div>
              <a-link
                onClick={() => handleClick(record)}
                disabled={props.disabled}
              >
                查看组件
              </a-link>
              <a-link
                onClick={() => props.delLesionData(record.lesionValue)}
                disabled={props.disabled}
              >
                删除
              </a-link>
            </div>
          ),
        }}
      ></Table>
      {/* 查看当前小征象组件弹窗 */}
      <Dialog
        title="查看已添加的标注数据"
        isForm={false}
        width={790}
        visible={visible.value}
        onUpdate:visible={handleUpdateVisible}
      >
        {{
          default: () => (
            <div class="view-dialog-body">
              <SeriesTable
                {...{
                  ...props,
                  data: currentItem.value.imageDataList,
                  flag: false,
                  handleSecondClick,
                  current: currentItem.value,
                }}
              />
            </div>
          ),
        }}
      </Dialog>
      {/* 查看标注字段弹窗 */}
      <Dialog
        title="查看标注字段"
        isForm={false}
        width={790}
        visible={secondVisible.value}
        onUpdate:visible={handleSecondUpdateVisible}
      >
        {{
          default: () => (
            <div class="view-dialog-body">
              <SecondAlert data={secondCurrentData.value} />
            </div>
          ),
        }}
      </Dialog>
    </>
  );
};

const getOptions = (
  data,
  index: number,
  tableData: LesionDataList[],
  flag = false
) => {
  // 处理同上一个病灶选择
  const handleClick = (
    index: number,
    tableData: LesionDataList[],
    flag = false
  ) => {
    if (flag) {
      // 为true 是标注工具同上一个病灶操作
      tableData[index].toolValueList = JSON.parse(
        JSON.stringify(tableData[index - 1].toolValueList)
      );
    }
    if (!flag) {
      // 为false 是标注组件同上一个病灶操作
      tableData[index].imageList = JSON.parse(
        JSON.stringify(tableData[index - 1].imageList)
      );
      tableData[index].imageDataList = JSON.parse(
        JSON.stringify(tableData[index - 1].imageDataList)
      );
      tableData[index].imageFcList = JSON.parse(
        JSON.stringify(tableData[index - 1].imageFcList)
      );
    }
  };
  if (index !== 0) {
    return (
      <>
        <div
          class="arco-select-option arco-select-option-multiple"
          onClick={() => handleClick(index, tableData, flag)}
        >
          <div style="padding-left: 26px">同上一个病灶</div>
        </div>
        {data.map((item) => (
          <a-option value={item.value}>{item.name}</a-option>
        ))}
      </>
    );
  } else {
    return data.map((item) => (
      <a-option value={item.value}>{item.name}</a-option>
    ));
  }
};

const getOpts = (data) => {
  return data.map((item) => (
    <a-option value={item.value}>{item.name}</a-option>
  ));
};

const changeData = (data, flag = false) => {
  if (flag) {
    return data.map((item) => ({ name: item.name, value: +item.value }));
  } else {
    return data.map((item) => ({ value: item.id, name: item.name }));
  }
};

export default AnnoTable;
